package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"projectes/models/mysql"
	"projectes/models/redis"
	"projectes/projectrpc/internal/svc"
	"projectes/projectrpc/projectrpc"
	"strconv"
	"time"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *projectrpc.ProductListRequest) (*projectrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	var Products []mysql.Product
	var count int64
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	itoa := strconv.Itoa(int(offset))
	mysql.DB.Debug().Model(&Products).Count(&count)
	get := redis.Client.Get("list" + itoa)

	if get.Val() == "" {
		mysql.DB.Debug().Model(&Products).Limit(int(in.Size)).Offset(int(offset)).Where("product_name like ?", "%"+in.ProductName+"%").Order("price desc").Find(&Products)
		marshal, _ := json.Marshal(&Products)
		redis.Client.Set("list"+itoa, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &Products)

	}

	var sliceStruct []*projectrpc.ProductListStruct

	for _, product := range Products {
		list := &projectrpc.ProductListStruct{
			Sort:        product.Sort,
			ProductCode: product.ProductCode,
			ProductName: product.ProductName,
			Number:      int64(product.Number),
			Price:       float32(product.Price),
			Cost:        int64(product.Cost),
			Img:         product.Img,
			UserId:      int64(product.UserId),
		}
		sliceStruct = append(sliceStruct, list)
	}

	return &projectrpc.ProductListResponse{Lists: sliceStruct, Total: count}, nil
}
